<template>
  <el-container>
    <el-aside style="float: left;width: 300px;">
      <!-- 头部操作按钮 -->
      <el-card class="box-card el-card-flex">
        <div slot="header" class="clearfix">
          <el-input
            v-model="searchValue"
            placeholder="请搜索..."
            suffix-icon="el-icon-search"
          ></el-input>
        </div>
        <div slot="header" class="clearfix"></div>
        <div class="text item el-over-auto">
          <!-- Tree 树形控件 -->
          <el-tree
            :data="searchData"
            :props="defaultProps"
            node-key="dictId"
            @node-click="handleNodeClick"
            v-show="searchValue"
            :ref="searchValue? 'orgTree':''"
            :highlight-current="true"
            default-expand-all
          />
          <el-tree
            :key="treeKey"
            :props="defaultProps"
            node-key="dictId"
            @node-click="handleNodeClick"
            :ref="!searchValue? 'orgTree':''"
            :highlight-current="true"
            :load="loadNode1"
            v-show="!searchValue"
            lazy
          />
        </div>
      </el-card>
    </el-aside>
    <el-main style="padding: 0 0 0 10px;">
      <el-card class="box-card el-card-flex">
        <div slot="header" class="clearfix">
          <span>
            <i class="el-icon-warning-outline"></i> 字典信息
          </span>
          <div style="float: right">
            <el-button type="primary" plain @click="newModal">
              新增
              <i class="el-icon-plus"></i>
            </el-button>
            <el-button v-show="!showBtn" type="primary" plain @click="amend" style="margin-left: 5px;">
              编辑
              <i class="el-icon-edit"></i>
            </el-button>
            <el-button v-show="showBtn" type="primary" plain @click="btnSave" style="margin-left: 5px;">
              保存
              <i class="el-icon-document-checked el-icon--right"></i>
            </el-button>
            <el-button v-show="showBtn" type="info" plain @click="btnCencel" style="margin-left: 5px;">
              取消
              <i class="el-icon-refresh"></i>
            </el-button>
            <el-button type="danger" plain @click="removeTree()" style="margin-left: 5px;">
              删除
              <i class="el-icon-delete"></i>
            </el-button>
          </div>
        </div>
        <div class="text item el-over-auto" style="padding:10px 50px">
          <el-form label-width="80px" class="el-flex-none" v-show="!showVal">
            <el-form-item label="主键:">
              <el-col :span="12">
                <span>{{formObj.dictId}}</span>
              </el-col>
            </el-form-item>
            <el-form-item label="编码:">
              <el-col :span="12">
                <span>{{formObj.dictTypeId}}</span>
              </el-col>
            </el-form-item>
            <el-form-item label="名称:">
              <el-col :span="12">
                <span>{{formObj.dictName}}</span>
              </el-col>
            </el-form-item>
            <el-form-item label="排序号:">
              <el-col :span="12">
                <span>{{formObj.sortNo}}</span>
              </el-col>
            </el-form-item>
            <el-form-item label="是否启用:">
              <span>{{formObj.enableFlag=='Y'?'启用':'禁用'}}</span>
            </el-form-item>
          </el-form>
          <el-form label-width="80px" :model="formObj" ref="formObj" class="el-flex-none" v-show="showVal">
              <el-form-item label="主键:" prop="dictId">
              <el-col :span="12">
                <el-input v-model="formObj.dictId" readonly></el-input>
              </el-col>
            </el-form-item>
            <el-form-item label="编码:" prop="dictTypeId">
              <el-col :span="12">
                <el-input v-model="formObj.dictTypeId" readonly></el-input>
              </el-col>
            </el-form-item>
            <el-form-item
              label="名称:"
              prop="dictName"
              :rules="[
                {
                  required: true,
                  message: '名称不能为空'
                }
              ]"
              >
              <el-col :span="12">
                <el-input v-model="formObj.dictName"></el-input>
              </el-col>
            </el-form-item>
            <el-form-item label="排序号:" prop="sortNo">
              <el-col :span="12">
                <el-input-number
                  v-model="formObj.sortNo"
                  :min="0"
                  :step="1"
                  step-strictly
                ></el-input-number>
              </el-col>
            </el-form-item>
            <el-form-item label="是否启用:" prop="enableFlag">
              <el-switch
                v-model="formObj.enableFlag"
                active-value="Y"
                inactive-value="N"
              ></el-switch>
            </el-form-item>
          </el-form>
          <div style="text-align:right;"></div>
          <div class="el-flex el-box-column"></div>
        </div>
      </el-card>
      <!-- 模态框 -->
      <el-dialog
        title="字典信息"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :before-close="handleClose"
      >
        <el-form :model="orgForm" label-width="80px" :rules="rules" ref="orgForm">
          <el-form-item
            label="名称:"
            prop="dictName"
            :rules="[
              {
                required: true,
                message: '名称不能为空',
                trigger: 'blur'
              }
            ]"
          >
            <el-col :span="15">
              <el-input placeholder="请输入名称" v-model="orgForm.dictName" autocomplete="off"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item
            label="编码:"
            prop="dictTypeId"
            :rules="[
              {
                required: true,
                message: '编码不能为空',
                trigger: 'blur'
              }
            ]"
          >
            <el-col :span="12">
              <el-input
                placeholder="请输入编码"
                v-model="orgForm.dictTypeId"
                autocomplete="off"
                :readonly="readonlyId"
              ></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="排序号:">
              <el-col :span="12">
                <el-input-number
                  v-model="orgForm.sortNo"
                  :min="0"
                  :step="1"
                  step-strictly
                ></el-input-number>
              </el-col>
            </el-form-item>
          <el-form-item label="上级类型:">
            <el-col :span="15">
              <el-input
                v-model="orgForm.parentName"
                placeholder="请输入上级类型"
                readonly
              >
                <i v-show="orgForm.parentName" slot="suffix" class="el-input__icon el-icon-circle-close" @click="clearParentName" style="cursor: pointer;"></i>
                <el-button slot="append" icon="el-icon-search" @click="dialogClick"></el-button>
              </el-input>
              <!-- <el-input type="hidden" v-model="orgForm.parentId"></el-input> -->
            </el-col>
          </el-form-item>
          <el-form-item label="是否启用:">
            <el-col :span="15">
              <el-switch v-model="orgForm.enableFlag" active-value="Y" inactive-value="N"></el-switch>
            </el-col>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleCheckSure">
            确定
            <i class="el-icon-document-checked el-icon--right"></i>
          </el-button>
          <el-button @click="handleCheckClose()">
            取消
            <i class="el-icon-refresh-left"></i>
          </el-button>
        </div>
      </el-dialog>
      <elDialog :key="elDialogTreeKey" @dialogHide="dialogHandleCheckSure" :dialogVisible="isShow"></elDialog>
    </el-main>
  </el-container>
</template>
<script>
import {
  Tree,
  Dialog,
  Table,
  TableColumn,
  Pagination,
  MessageBox,
  Message,
} from 'element-ui'
import elDialog from './dialog2'
import {dictSearch, dictDel, allRootDict, children, eosDictDetails, eosDictSvOrUp, eosDictNext} from '@/api/system/wordbook/wordbook.js'
export default {
  name: 'wordbook2',
  components: {
    'el-tree': Tree, // 树形菜单
    'el-dialog': Dialog, // 对话框
    'el-table': Table, // 表格
    'el-table-column': TableColumn, // 表格列
    'el-pagination': Pagination, // 分页
    elDialog,
  },
  data () {
    return {
      // cencelBtn: false, // 是否显示取消按钮
      showVal: '',
      isShow: false, // 判断组件案例的弹框是否展示
      inpDialog: false,
      readonly: true, // input框是否只读
      readonlyId: false,
      data: [], // 侧边栏数据
      defaultProps: {
        label: 'dictName',
        isLeaf: 'leaf'
      },
      treeKey: 1,
      addTabelData: {
        // 新增空数组
        coding: '',
        name: ''
      },
      orgForm: {
        parentId: '',
        parentName: '',
        dictName: '',
        dictTypeId: '',
        sortNo: '',
        enableFlag: 'Y'
      }, // 值集信息模态框里定义的对象
      search: false,
      showBtn: '', // 判断编辑和保存按钮的展示
      searchValue: '', // 搜索框定义的默认属性
      dialogVisible: false, // 弹框是否显示
      dialogFormVisible: false, // 模态框隐藏
      formObj: {},
      rules: {},
      nowDelId: '',
      editName: '',
      nowDictTypeId: '',
      tableData: [], // 表格数据
      typeid: '', // 从子集获取过来的dictTypeId
      dictParentId: '',
      depClone: {}, // 取消时拷贝this.formObj
      elDialogTreeKey: 3,
      searchData: [], // 搜索后的tree数据
      parentDataClone: [], // 再获取一份父节点数据
    }
  },
  watch: {
    // 搜索监听事件
    searchValue (val) {
      if (val) {
        dictSearch({ dictName: this.searchValue })
        .then(res => {
          let eosDictDatas = res.data.data
          this.deepChild(eosDictDatas)
          this.searchData = eosDictDatas
          // this.formObj = JSON.parse(JSON.stringify(eosDictDatas[0]));
        })
      } else {
        this.treeKey += 1 // 刷新树
      }
    }
  },
  created () {},
  methods: {
    /* 递归遍历树形数据源 */
    deepChild (val) {
      let $this = this
      if (val && Array.isArray(val) && val.length) {
        val.forEach(item => {
          if (typeof item === 'object') {
            item.dictId = item.id
            item.dictName = item.name
            $this.deepChild(item.children)
          }
        })
      }
    },
    /* 过滤无效数据*/
    filterInvalid (dataSource) {
      let validData = {}
      let jsonData = JSON.stringify(dataSource)
      for (let k in dataSource) {
        let data = dataSource[k]
        if (data != "" && data != null && data != undefined && jsonData != "{}" && jsonData != "[]") {
          validData[k] = data
        }
      }
      return validData
    },
    dialogClick () {
      this.isShow = true
    },
    dialogHandleCheckSure (result) {
      // console.log(result)
      this.isShow = false
      // if (!result) return console.log('点击了取消', result)
      // if (this.orgForm.parentName) {
      //   this.readonlyId = false
      // } else {
      //   this.readonlyId = true
      // }
      if (!result) {
        // 如果未选中节点，则视为清空操作
        this.orgForm = {
          parentId: this.orgForm.parentId,
          dictTypeId: this.orgForm.dictTypeId,
          dictName: this.orgForm.dictName,
          enableFlag: 'Y'
        }
      }
      this.orgForm.parentId = result.dictId
      this.orgForm.parentName = result.dictName
      // this.orgForm.sortNo = result.sortNo
      // this.orgForm.enableFlag = result.enableFlag
      this.elDialogTreeKey++
      // this.orgForm.dictTypeId = result.dictTypeId
    },
    // 删除树节点事件
    removeTree () {
      MessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.delData()
        })
        .catch(() => {})
    },
    delData () {
      let getData = this.$refs.orgTree.getCurrentNode() // 获取到删除节点信息
      let dictId = getData.dictId // 得到节点id
      dictDel(dictId)
        .then(res => {
          if (res.data.code === 10000) {
            Message.success('删除成功')
          }
          // let getData = this.$refs.orgTree.getCurrentNode() // 获取到删除节点信息
          // let dictId = getData.dictId // 得到节点id
          let parentId = getData.parentId // 得到父节点id
          // console.log(parentId)
          if (!parentId) {
            let nodeData = this.$refs.orgTree.getNode(dictId)
            let pNode = nodeData.parent
            if (res.data.code === 10000) {
              this.$refs.orgTree.remove(dictId) // 删除得到节点id
            }
            // this.$refs.orgTree.remove(dictId) // 删除得到节点id
            // console.log(nodeData)
            parentId= pNode.childNodes[0].data.dictId
            // console.log(parentId)
          } else {
            if (res.data.code === 10000) {
              this.$refs.orgTree.remove(dictId) // 删除得到节点id
            }
            // this.$refs.orgTree.remove(dictId) // 删除得到节点id
          }
          this.$refs.orgTree.setCurrentKey(parentId)//删除后默认选中父节点
          this.formObj = JSON.parse(JSON.stringify(this.$refs.orgTree.getCurrentNode())) //更新表单数据
          this.showVal = false
        })
        .catch(error => {
          // console.log(error)
        })
    },
    newModal () {
      this.dialogFormVisible = true
      // 设置默认获取到值集上级类型
      this.orgForm = {}
      this.orgForm.enableFlag = 'Y'
      let getData = this.$refs.orgTree.getCurrentNode()
      // console.log(getData)
      if (getData) {
        this.orgForm.parentId = getData.dictId
        this.orgForm.parentName = getData.dictName
      }
    },
    loadNode1 (node, resolve) {
      // node.data && this.toJudge(node.data)
      // console.log(node.data)
      if (node.level === 0) {
        allRootDict().then(res => {
            let parentData = []
            res.data.data.forEach(e => {
              e.leaf = e.isLeaf === null || false
              parentData.push(e)
            })
            parentData.forEach(item => {
              // this.defaultArrId = [parentData[0].dictId]
              // console.log(item.dictId)
            })
            // console.log(parentData)
            this.parentDataClone = parentData
            this.orgForm = JSON.parse(JSON.stringify(this.parentDataClone[0]))
            // this.depClone = JSON.parse(JSON.stringify(this.orgForm))
            this.formObj = this.orgForm
            resolve(this.parentDataClone)
            this.$refs.orgTree.setCurrentKey(this.orgForm.dictId)
            // this.nowDictTypeId = this.orgForm.dictId
            // this.nowDelId = this.orgForm.dictTypeId
          })
          .catch(res => {
            resolve([])
          })
      } else {
        // console.log(' 当前节点id值为：' + node.data.dictId)
        let id = node.data.dictId
        children(id)
          .then(res => {
            let childrenList = []
            res.data.data.forEach(e => {
              e.leaf = e.isLeaf === null || false
              childrenList.push(e)
            })
            resolve(childrenList)
          })
          .catch(res => {
            resolve([])
          })
      }
    },
    // 点击侧边栏触发事件
    handleNodeClick (nodeObj, node) {
      // this.defaultArrId = this.node.data.dictTypeId
      // console.log(nodeObj)
      this.toJudgeClick(nodeObj)
    },
    // 判断选中的发生了变化
    // toJudge (nodeObj) {
    //   // console.log(nodeObj)
    //   if (this.nowDictTypeId === nodeObj.dictId) return false
    //   else {
    //     this.nowDictTypeId = nodeObj.dictId
    //     this.delId = nodeObj.dictTypeId
    //     this.editName = nodeObj.dictName
    //     // if (nodeObj.rank === 1) { // 点击的是父级别的节点
    //     let tempObj = {
    //       dictId: nodeObj.dictId,
    //       dictTypeId: nodeObj.dictTypeId,
    //       dictName: nodeObj.dictName
    //     }
    //     if (nodeObj.sortNo) {
    //       tempObj.sortNo = nodeObj.sortNo
    //     }
    //     if (nodeObj.enableFlag) {
    //       tempObj.enableFlag = nodeObj.enableFlag
    //     }
    //     console.log(tempObj)
    //     this.depClone = JSON.parse(JSON.stringify(tempObj))
    //     this.formObj = tempObj
    //   }
    // },
    toJudgeClick (nodeObj) {
      this.btnCencel()
      // console.log(nodeObj)
      // this.nowDictTypeId = nodeObj.dictId
      // this.nowDelId = nodeObj.dictTypeId
      // let id = nodeObj.dictId
      eosDictDetails(nodeObj.dictId).then(res => {
        // console.log(res)
        this.depClone = JSON.parse(JSON.stringify(res.data.data))
        this.formObj = res.data.data
        // 设置默认获取到值集上级类型
        let getData = this.$refs.orgTree.getCurrentNode()
        // console.log(getData)
        if (getData) {
          this.orgForm.parentName = getData.dictName
        }
      })
    },
    // 编辑事件
    amend () {
      this.showVal = true
      // this.cencelBtn = true
      this.showBtn = true
    },
    // 取消事件
    btnCencel () {
      this.$refs.formObj.resetFields() //清空校验
      this.formObj = JSON.parse(JSON.stringify(this.$refs.orgTree.getCurrentNode())) //重新赋值
      this.showVal = false
      // this.cencelBtn = false
      this.showBtn = false
      // this.formObj = JSON.parse(JSON.stringify(this.depClone))
    },
    // 保存事件
    btnSave () {
      let getData = this.$refs.orgTree.getCurrentNode() // 获取到节点信息
      let dictId = getData.dictId // 得到节点id
      let dictTypeId = getData.dictTypeId // 得到节点dictTypeId
      this.$refs.formObj.validate(valid => {
        if (!valid) return false
        eosDictSvOrUp({
            dictId: dictId,
            dictTypeId: dictTypeId,
            dictName: this.formObj.dictName,
            sortNo: this.formObj.sortNo,
            enableFlag: this.formObj.enableFlag
          })
          .then(res => {
            Message.success('保存成功')
            // console.log(res.data.code)
            this.showVal = false
            // this.cencelBtn = false
            // this.treeKey += 1
            let getData = this.$refs.orgTree.getCurrentNode()
            Object.assign(getData, this.formObj)
            this.showBtn = false
          })
          .catch(error => {
            // console.log(error, '失败')
          })
        this.showBtn = true
      })
    },
    // 编辑弹框确认
    handleCheck () {
      this.tableData[this.index] = this.addTabelData
      this.dialogVisible = false
    },
    // 弹框确认
    handleCheckSure () {
      // console.log('111')
      // if (!this.dictParentId) {
      this.$refs.orgForm.validate(valid => {
        if (valid) {
          if (this.orgForm.parentId) {
            eosDictNext(this.orgForm)
              .then(res => {
                // console.log(res)
                if (res.data.code === 10000) {
                  this.dialogFormVisible = false
                  // this.treeKey += 1
                  // this.orgForm.leaf = true
                  this.orgForm.dictId = res.data.data
                  let orgFormData =  JSON.parse(JSON.stringify(this.orgForm))
                  orgFormData.isLeaf = null // 新增的节点默认为叶子节点
                  orgFormData.leaf = true // 新增的节点默认为叶子节点
                  orgFormData.dictId = res.data.data //保存id
                  let pId = orgFormData.parentId //获取要新增的父节点id
                  if (pId) {//已知父节点新增子节点
                    let pNode = this.$refs.orgTree.getNode(pId)
                    if (pNode.isLeaf) { //如果是叶子节点
                      pNode.isLeaf = false
                      pNode.leaf = false
                      pNode.isLeafByUser = false //设置为非叶子节点
                      pNode.loaded = true //设置为已加载状态
                      pNode.expanded = true //设置父节点展开
                    }
                    this.$refs.orgTree.append(orgFormData, pId)
                  }
                  // let orgTreeData = this.$refs.orgTree.getCurrentNode()
                  // this.$refs.orgTree.append(orgFormData, orgTreeData) // 手动插入树节点，不刷新树
                }
                this.handleCheckClose()
              })
            this.dialogFormVisible = false
          } else {
            eosDictSvOrUp(this.filterInvalid(this.orgForm))
            .then(res => {
              // console.log(res)
              if (res.data.code === 10000) {
                this.dialogFormVisible = false
                this.treeKey += 1
              }
              this.handleCheckClose()
            })
          }
        } else {
          return false
        }
      })
    },
    // 第一个弹框取消事件
    handleCheckClose () {
      this.$refs.orgForm.resetFields()
      this.readonlyId = false
      // this.orgForm = {}
      // this.orgForm.enableFlag = 'Y'
      this.dialogFormVisible = false
    },
    // 弹框关闭事件
    close () {
      this.$refs.orgForm.resetFields()
      // this.orgForm = {}
      this.dialogFormVisible = false
    },
    // 编辑弹框关闭提示框
    handleClose () {
      // MessageBox.confirm('确认关闭字典信息弹框吗？')
      //   .then(_ => {
          this.handleCheckClose()
        // })
        // .catch(_ => {})
    },
    // 新增时，清空上级类型
    clearParentName () {
      // this.orgForm.parentId = ''
      // this.orgForm.parentName = ''
      this.orgForm = {
        parentName: '',
        parentId: '',
        dictName: this.orgForm.dictName,
        dictTypeId: this.orgForm.dictTypeId,
        sortNo: this.orgForm.sortNo,
        enableFlag: 'Y'
      }
    }
  }
}
</script>
<style lang="scss">
.el-button.el-button-pad {
	padding-left: 8px;
	padding-right: 8px;
}
</style>
